import os
import asyncio
import json
from pathlib import Path
from playwright.async_api import async_playwright, TimeoutError as PlaywrightTimeoutError
import logging
import time
import sys
sys.path.append(str(Path(__file__).resolve().parent))
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from myxhs import check_login
from call_coze import get_coze_xhs_data

MYXHS_PATH = Path(__file__).resolve().parent / "cookies" / "myxhs.json"
LOG_PATH = Path(__file__).resolve().parent / "cookies" / "myxhs2.log"

current_path = os.path.dirname(os.path.abspath(__file__))



logging.basicConfig(filename=LOG_PATH, level=logging.ERROR, format='%(asctime)s %(levelname)s %(message)s')

async def wait_and_click(page, selector, timeout=3000, max_retries=10):
    retry = 0
    while True:
        try:
            await page.wait_for_selector(selector, timeout=timeout)
            await page.click(selector)
            print(f"点击成功: {selector}")
            break
        except PlaywrightTimeoutError as e:
            logging.error(f"Timeout waiting for {selector}, retry {retry+1}: {e}")
            retry += 1
            if retry >= max_retries:
                print(f"重试{max_retries}次后仍未找到 {selector}，请检查页面。")
                break
        except Exception as e:
            logging.error(f"Exception on {selector}, retry {retry+1}: {e}")
            retry += 1
            if retry >= max_retries:
                print(f"重试{max_retries}次后仍未找到 {selector}，请检查页面。")
                break

async def wait_and_click_locator(page, selector, timeout=3000, max_retries=10):
    retry = 0
    while True:
        try:
            await page.locator(selector).wait_for(timeout=timeout)
            await page.locator(selector).click()
            print(f"点击成功: {selector}")
            break
        except PlaywrightTimeoutError as e:
            logging.error(f"Timeout waiting for {selector}, retry {retry+1}: {e}")
            retry += 1
            if retry >= max_retries:
                print(f"重试{max_retries}次后仍未找到 {selector}，请检查页面。")
                break
        except Exception as e:
            logging.error(f"Exception on {selector}, retry {retry+1}: {e}")
            retry += 1
            if retry >= max_retries:
                print(f"重试{max_retries}次后仍未找到 {selector}，请检查页面。")
                break

import sys

# 读取配置文件
CONFIG_PATH = Path(__file__).resolve().parent / "config.json"
def load_config():
    if not CONFIG_PATH.exists():
        print(f"配置文件 {CONFIG_PATH} 不存在，请先创建！")
        sys.exit(1)
    with open(CONFIG_PATH, "r", encoding="utf-8") as f:
        return json.load(f)

config = load_config()
api_token = config.get("api_token", "")
workflow_id = config.get("workflow_id", "")
wx_who = config.get("who", "文件传输助手")


def ensure_playwright_browsers():
    try:
        from playwright.__main__ import main as playwright_main
        # 检查是否已安装浏览器（简单做法：尝试调用，若失败则安装）
        import shutil
        import os
        browser_path = os.path.expanduser("~/.cache/ms-playwright/chromium")
        if not os.path.exists(browser_path) or not os.listdir(browser_path):
            print("未检测到 Playwright 浏览器，正在自动安装...")
            sys.argv = ["playwright", "install", "chromium"]
            playwright_main()
    except Exception as e:
        print("Playwright 浏览器安装失败，请手动运行: playwright install")
        print(e)
        sys.exit(1)

async def main():
    myxhs_data = get_coze_xhs_data(api_token, workflow_id=workflow_id)
    print("获取到coze生成的", myxhs_data)
    if not myxhs_data:
        print("未获取到小红书内容，程序退出")
        return
    # 登录并保存cookie
    for i in range(3):
        result = await check_login(wx_who=wx_who)
        if result:
            print("不需要登录")
            break
        print(f"第{i+1}次登录失败，重试...")
    else:
        print("连续3次登录失败，程序退出")
        return
    # 读取cookie和user_agent，自己新建浏览器
    with open(MYXHS_PATH, "r", encoding="utf-8") as f:
        data = json.load(f)
    cookies = data["cookies"]
    user_agent = data["user_agent"]
    async with async_playwright() as p:
        print("[DEBUG] playwright started")
        browser = await p.chromium.launch(headless=False)
        print("[DEBUG] browser launched")
        context = await browser.new_context(user_agent=user_agent)
        print("[DEBUG] context created")
        await context.add_cookies(cookies)
        print("[DEBUG] cookies added")
        page = await context.new_page()
        print("[DEBUG] new page created")
        await page.goto("https://creator.xiaohongshu.com/new/home")
        print("[DEBUG] page.goto finished, 已成功访问 https://creator.xiaohongshu.com/new/home")
        # 点发布笔记
        await wait_and_click(page, ".publish-video>.btn", timeout=3000)
        print("[DEBUG] clicked .publish-video>.btn")
        # 用xpath点击上传图文tab
        xpath = '//*[@id="web"]//div[@class="creator-tab" and not(@style)]//span[@class="title" and text()="上传图文"]'
        try:
            await page.wait_for_selector(f'xpath={xpath}', timeout=3000)
            print(f"[DEBUG] xpath {xpath} appeared")
            await page.locator(f'xpath={xpath}').click()
            print(f"[DEBUG] clicked xpath {xpath}")
        except Exception as e:
            logging.error(f"点击xpath {xpath} 失败: {e}")
            print(f"点击xpath {xpath} 失败: {e}")
        # 上传文件
        file_path = os.path.join(current_path, "header.jpg")
        await page.set_input_files(".upload-input", file_path)
        # 使用 myxhs_data 输入标题和内容
        title = myxhs_data.get("title", "")
        await page.wait_for_selector(".titleInput .d-text", timeout=3000)
        await page.fill(".titleInput .d-text", title)
        await page.click("#quillEditor")
        await page.keyboard.type(f'{myxhs_data["content"]}\n\n')
        # 添加话题标签
        topics = myxhs_data["tags"]
        for topic in topics:
            print(f"添加话题: {topic}")
            await page.keyboard.type("#")
            time.sleep(1)
            await page.keyboard.type(topic)
            time.sleep(1)
            try:
                await page.locator("#quill-mention-list li:first-child").click()
                time.sleep(1)
            except:
                print(f"话题 '{topic}' 未找到，将作为普通文本输入")
                page.keyboard.press("Escape")
        print("话题标签已成功添加到编辑器中！")
        await page.locator('xpath=//div[contains(@class, "d-button-content")]/span[text()="发布"]').click()
        print("已点击发布按钮")
        print("请在浏览器中继续完成笔记发布流程...")
        await asyncio.sleep(3)
        await context.close()
        await browser.close()
        sys.exit(0)

if __name__ == "__main__":
    asyncio.run(main())
